/**
 * 
 */
package com.moioo.util;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.hibernate.Transaction;

import com.moioo.exam.TMenu;
import com.moioo.exam.TOrgan;
import com.moioo.exam.TOrganDAO;
import com.moioo.exam.TUser;
import com.moioo.exam.TUserDAO;
import com.moioo.exam.TUserLog;
import com.moioo.exam.TUserLogDAO;
import com.moioo.vod.action.UserLogAction;

/**
 * @author 3400423@qq.com
 *
 */
public class ActionBase extends DispatchAction{
	public User getUser(HttpServletRequest request){
		return User.get(request);
	}
	public ActionForward wrong(String msg , String backurl,ActionMapping mapping,HttpServletRequest request,HttpServletResponse response){
		request.setAttribute("errMsg", msg);
		return mapping.findForward("wrong1.msg");
	}
	public ActionForward noaccess(ActionMapping mapping){
		return mapping.findForward("noaccess.msg");
	}
	public void setMsg(String msg ,HttpServletRequest request){
		request.setAttribute("errMsg", msg);
	}
	protected void setTableMenu(HttpServletRequest request,int id){
		User user = getUser(request);
		request.setAttribute("tableMenu", TMenu.getTableHtmlString(user,id));
	}
	public void online(HttpServletRequest request)
	{
		synchronized(UserLogAction.UserLogMap)
		{
			User user = getUser(request);
			if (user.getTag()>=0)
			{
				TUserLog userlog=UserLogAction.UserLogMap.get(user.getId()+"|"+user.getTag());
				if (userlog==null)
				{
					TUser tuser=new TUserDAO().findById(user.getId());
					TOrgan torgan=new TOrganDAO().findById(tuser.getOrgan());
				    userlog=new TUserLog(user.getId(),user.getName(),torgan.getId(),torgan.getName(),user.getIp());
				    UserLogAction.UserLogMap.put(user.getId()+"|"+user.getTag(), userlog);
				}else
				{
					userlog.setEndtime(new Date());
				}
			}
			System.out.println(user.getId()+"|"+user.getTag());
		}		
	}
	public void offline(HttpServletRequest request)
	{
		synchronized(UserLogAction.UserLogMap)
		{
			User user = getUser(request);
			if (user.getTag()>=0)
			{
				TUserLog userlog=UserLogAction.UserLogMap.remove(user.getId()+"|"+user.getTag());
				if (userlog!=null)
				{
					TUserLogDAO dao = new TUserLogDAO();
					Transaction tran = dao.getSession().beginTransaction();
					dao.save(userlog);
					tran.commit();
					dao.getSession().clear();				
				}
			}
		}		
	}
}
